package com.crowntit.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.crowntit.api.dto.NotifyRequestDTO;
import com.crowntit.domain.order.model.entity.GroupBuyNotifyEntity;
import com.crowntit.domain.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class TeamSuccessTopicListener {

    @Resource
    private IOrderService orderService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${spring.rabbitmq.config.consumer.topic_team_success.queue}"),
                    exchange = @Exchange(value = "${spring.rabbitmq.config.consumer.topic_team_success.exchange}", type = ExchangeTypes.TOPIC),
                    key = "${spring.rabbitmq.config.consumer.topic_team_success.routing_key}"
            ))
    public void listener(String message){
        log.info("接收到MQ消息，topic: team_success，message: {}", message);
        NotifyRequestDTO requestDTO = JSON.parseObject(message, NotifyRequestDTO.class);

        // 接收回调信息
        String teamId = requestDTO.getTeamId();
        List<String> outTradeNoList = requestDTO.getOutTradeNoList();
        String groupBuyTeamStatus = requestDTO.getStatus();

        // 参数判断
        if (outTradeNoList == null || outTradeNoList.isEmpty() || StringUtils.isBlank(groupBuyTeamStatus)) {
            log.error("团购回调-请求参数为空");
            return;
        }

        try {
            orderService.changeOrderGroupBuyTeamStatus(GroupBuyNotifyEntity.builder()
                    .gbmOutTradeNoList(outTradeNoList)
                    .groupBuyTeamStatus(groupBuyTeamStatus)
                    .build());
        } catch (Exception e) {
            log.error("团购回调-修改系统内订单状态时发生错误: {}", message, e);
        }
    }

}
